<?php

class openapi_data_original_basicmaterial{

    protected $_type = array(
        '1' => '普通',
        '2' => '组合',
    );

    protected $_visibled = array(
        '1' => '显示',
        '2' => '隐藏',
    );

    public function getList($filter,$offset=0,$limit=40){
        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj   = app::get('material')->model('basic_material_ext');
        $basicMaterialBarcodeLib = kernel::single('material_basic_material_barcode');

        $count = $basicMaterialObj->count($filter);

        if($count >0){
            $basicMaterialList = $basicMaterialObj->getList('*',$filter,$offset,$limit);

            $lists = array();
            foreach ($basicMaterialList as $basicMaterial) {
                $basicMExtInfo = $basicMaterialExtObj->getList('*' ,array('bm_id'=>$basicMaterial['bm_id']) ,0 ,1);
                $basicMBarcode = $basicMaterialBarcodeLib->getBarcodeById($basicMaterial['bm_id']);

                $lists[$basicMaterial['bm_id']]['material_name'] = $basicMaterial['material_name'];
                $lists[$basicMaterial['bm_id']]['material_bn'] = $basicMaterial['material_bn'];
                $lists[$basicMaterial['bm_id']]['visibled'] = $basicMaterial['visibled'];
                $lists[$basicMaterial['bm_id']]['serial_number'] = $basicMaterial['serial_number'];
                $lists[$basicMaterial['bm_id']]['type'] = $basicMaterial['type'];

                $lists[$basicMaterial['bm_id']]['cost'] = $basicMExtInfo[0]['cost'];
                $lists[$basicMaterial['bm_id']]['retail_price'] = $basicMExtInfo[0]['retail_price'];
                $lists[$basicMaterial['bm_id']]['weight'] = $basicMExtInfo[0]['weight'];
                $lists[$basicMaterial['bm_id']]['unit'] = $basicMExtInfo[0]['unit'];
                $lists[$basicMaterial['bm_id']]['barcode'] = $basicMBarcode;
            }

            return array(
                'lists' => $lists,
                'count' => $count,
            );
        }else{
            return array(
                'lists' => array(),
                'count' => 0,
            );
        }
    }

    /**
     * 基础物料新增时的参数检查方法
     * 
     * @param Array $params 
     * @param String $err_msg
     * @return Boolean
     */
    function checkAddParams(&$params, &$err_msg){
        if(empty($params['material_name']) || empty($params['material_bn']) || empty($params['material_code'])){
            $err_msg ="必填信息不能为空";
            return false;
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialInfo = $basicMaterialObj->getList('material_bn',array('material_bn'=>$params['material_bn']));
        if($basicMaterialInfo){
            $err_msg ="当前新增的物料编码已被使用，不能重复";
            return false;
        }

        $barcodeObj = app::get('material')->model('barcode');
        $barcodeInfo = $barcodeObj->getList('bm_id',array('code'=>$params['material_code']));
        if($barcodeInfo){
            $err_msg ="当前条码已被使用，不能重复";
            return false;
        }

        $params['material_bn_crc32'] = sprintf('%u',crc32($params['material_bn']));

        if($params['type'] == 2){
            if(!isset($params['at'])){
                $err_msg ="组合物料请至少设置一个物料明细内容";
                return false;
            }

            $basicM_bns = $tmp_at = array();
            foreach ($params['at'] as $bn => $val){
                if (count($params['at']) == 1){
                    if ($val <2){
                        $err_msg ="只有一种物料时，数量必须大于1";
                        return false;
                    }
                }else {
                    if ($val < 1){
                        $err_msg ="数量必须大于0";
                        return false;
                    }
                }

                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $tmp_at[$basicInfo[0]['bm_id']] = $val;
                    $basicM_bns[$bn] = $basicInfo[0]['bm_id'];
                }
            }
            unset($params['at']);
            $params['at'] = $tmp_at;
        }

        return true;
    }

    public function add($data,&$code,&$sub_msg){
        $result = array('rsp'=>'succ');

        if(!$this->checkAddParams($data, $error_msg)){
            $result['rsp'] = 'fail';
            $result['msg'] = $error_msg;
            return $result;
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');
        $codebaseObj = app::get('material')->model('codebase');

        //保存物料主表信息
        $addData = array(
            'material_name' => $data['material_name'],
            'material_bn' => $data['material_bn'],
            'material_bn_crc32' => $data['material_bn_crc32'],
            'serial_number' => $data['serial_number'] ? $data['serial_number'] : 'false',
            'type' => $data['type'],
            'visibled' => $data['visibled'],
            'create_time' => time(),
        );
        $is_save = $basicMaterialObj->save($addData);

        if($is_save){
            //保存物料条码信息
            $code_type = material_codebase::getBarcodeType();
            $addCodeData = array(
                'bm_id' => $addData['bm_id'],
                'type' => $code_type,
                'code' => $data['material_code'],
            );

            $codebaseObj->insert($addCodeData);
            //保存保质期配置
            $useExpireConfData = array(
                'bm_id' => $addData['bm_id'],
                'use_expire' => $data['use_expire'] == 1 ? 1 : 2,
                'warn_day' => $data['warn_day'] ?  $data['warn_day'] : 0,
                'quit_day' => $data['quit_day'] ? $data['quit_day'] : 0,
                'create_time' => time(),
            );
            $basicMaterialConfObj->save($useExpireConfData);

            //如果是组合物料保存相关数据
            if($addData['type'] == 2){
                $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');
                foreach($data['at'] as $k=>$v){
                    $tmpChildMaterialInfo = $basicMaterialObj->dump($k, 'material_name,material_bn');

                    $addCombinationData = array(
                        'pbm_id' => $addData['bm_id'],
                        'bm_id' => $k,
                        'material_num' => $v,
                        'material_name' => $tmpChildMaterialInfo['material_name'],
                        'material_bn' => $tmpChildMaterialInfo['material_bn'],
                        'material_bn_crc32' => sprintf('%u',crc32($tmpChildMaterialInfo['material_bn'])),
                    );
                    $basicMaterialCombinationItemsObj->insert($addCombinationData);
                    $addCombinationData = null;
                }
            }

            //保存基础物料的关联的特性
            if($data['ftgp_id']){
                $addBindFeatureData = array(
                    'bm_id' => $addData['bm_id'],
                    'feature_group_id' => $data['ftgp_id'],
                );
                $basicMaterialFeatureGrpObj->insert($addBindFeatureData);
                $addBindFeatureData = null;
            }

            //保存物料扩展信息
            $addExtData = array(
                'bm_id' => $addData['bm_id'],
                'cost' => $data['cost'] ? $data['cost'] : 0.00,
                'retail_price' => $data['retail_price'] ? $data['retail_price'] : 0.00,
                'weight' => $data['weight'] ? $data['weight'] : 0.00,
                'unit' => $data['unit'],
            );
            $basicMaterialExtObj->insert($addExtData);
            
            //保存物料库存信息
            $addStockData = array(
                'bm_id' => $addData['bm_id'],
                'store' => $data['store'],
                'store_freeze' => $data['store_freeze'],
            );
            $basicMaterialStockObj->insert($addStockData);
        }else{
            $result = array('msg'=>'基础物料添加失败', 'rsp'=>'fail');
        }

        return $result;
    }

    /**
     * 基础物料编辑时的参数检查方法
     * 
     * @param Array $params 
     * @param String $err_msg
     * @return Boolean
     */
    function checkEditParams(&$params, &$err_msg){

        if(empty($params['material_name']) || empty($params['material_bn'])){
            $err_msg ="必填信息不能为空";
            return false;
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExistInfo = $basicMaterialObj->getList('bm_id',array('material_bn'=>$params['material_bn']));
        if(!$basicMaterialExistInfo){
            $err_msg ="当前物料不存在";
            return false;
        }else{
            $params['bm_id'] = $basicMaterialExistInfo[0]['bm_id'];
            $params['old_bm_info'] = $basicMaterialExistInfo[0];
        }

        if($params['type'] == 2){
            if(!isset($params['at'])){
                $err_msg ="组合物料请至少设置一个物料明细内容";
                return false;
            }

            $basicM_bns = $tmp_at = array();
            foreach ($params['at'] as $val){
                if (count($params['at']) == 1){
                    if ($val <2){
                        $err_msg ="只有一种物料时，数量必须大于1";
                        return false;
                    }
                }else {
                    if ($val < 1){
                        $err_msg ="数量必须大于0";
                        return false;
                    }
                }

                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $tmp_at[$basicInfo[0]['bm_id']] = $val;
                    $basicM_bns[$bn] = $basicInfo[0]['bm_id'];
                }
            }
        }

        return true;
    }

    /**
     * 检查基础物料个别参数是否可编辑
     * 
     * @param Int $bm_id
     * @return Array
     */
    function checkEditReadOnly($bm_id){
        $readonly = array('type' => false);

        //如果基础物料有库存、冻结、采购、订单，那么物料类型不能变
        $basicMStockObj = app::get('material')->model('basic_material_stock');
        $storeInfo = $basicMStockObj->getList('store,store_freeze',array('bm_id'=>$bm_id));
        if($storeInfo[0]['store'] > 0 || $storeInfo[0]['store_freeze'] > 0){
            $is_type_readonly = true;
        }

        $purchaseItemObj = app::get('purchase')->model('po_items');
        $purchaseInfo = $purchaseItemObj->getList('product_id',array('product_id'=>$bm_id));
        if($purchaseInfo){
            $is_type_readonly = true;
            $is_use_expire_readonly = true;
        }

        $orderItemObj = app::get('ome')->model('order_items');
        $orderInfo = $orderItemObj->getList('product_id',array('product_id'=>$bm_id));
        if($orderInfo){
            $is_type_readonly = true;
        }

        //如果有批次明细就不能变更保质期的开关
        $basicMaterialStorageLifeObj = app::get('material')->model('basic_material_storage_life');
        $expireItemsInfo = $basicMaterialStorageLifeObj->getList('bm_id',array('bm_id'=>$bm_id));
        if($expireItemsInfo){
            $is_use_expire_readonly = true;
        }

        //类目绑定后什么情况下可以解绑换成别的?需要判断么?

        if($is_type_readonly){
            $readonly['type'] = true;
        }

        if($is_use_expire_readonly){
            $readonly['use_expire'] = true;
        }

        return $readonly;
    }

    public function edit($data,&$code,&$sub_msg){
        $result = array('rsp'=>'succ');

        //检查参数
        if(!$this->checkEditParams($data, $error_msg)){
            $result['rsp'] = 'fail';
            $result['msg'] = $error_msg;
            return $result;
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');

        //检查部分按钮是否只读不可能修改
        $readonly = $this->checkEditReadOnly($data['bm_id']);
        $data['type'] = $readonly['type'] ? $data['old_bm_info']['type'] : $data['type'];

        $old_bm_cnf = $basicMaterialConfObj->dump($data['bm_id']);
        $data['use_expire'] = $readonly['use_expire'] ? $old_bm_cnf['use_expire'] : $data['use_expire'];

        //更新基础物料基本信息
        $updateData['material_name'] = $data['material_name'];

        if($data['serial_number']){
            $updateData['serial_number'] = $data['serial_number'];
        }

        $updateData['type'] = $data['type'];
        $updateData['visibled'] = $data['visibled'];
        $filter['bm_id'] = $data['bm_id'];

        $is_update = $basicMaterialObj->update($updateData,$filter);
        if($is_update){
            //保存保质期配置
            $useExpireConfData = array(
                'bm_id' => $filter['bm_id'],
                'use_expire' => $data['use_expire'] == 1 ? 1 : 2,
                'warn_day' => $data['warn_day'] ?  $data['warn_day'] : 0,
                'quit_day' => $data['quit_day'] ? $data['quit_day'] : 0,
            );

            $basicMaterialConfObj->save($useExpireConfData);
            //如果是组合物料保存相关数据
            if($updateData['type'] == 2){
                $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');
                //删除原有组合明细内容
                $basicMaterialCombinationItemsObj->delete(array('pbm_id'=>$filter['bm_id']));

                foreach($data['at'] as $k=>$v){
                    $tmpChildMaterialInfo = $basicMaterialObj->dump($k, 'material_name,material_bn');

                    $addCombinationData = array(
                        'pbm_id' => $filter['bm_id'],
                        'bm_id' => $k,
                        'material_num' => $v,
                        'material_name' => $tmpChildMaterialInfo['material_name'],
                        'material_bn' => $tmpChildMaterialInfo['material_bn'],
                        'material_bn_crc32' => sprintf('%u',crc32($tmpChildMaterialInfo['material_bn'])),
                    );
                    $basicMaterialCombinationItemsObj->insert($addCombinationData);
                    $addCombinationData = null;
                }
            }

            //删除原有的关联特性
            $basicMaterialFeatureGrpObj->delete(array('bm_id'=>$filter['bm_id']));
            //保存基础物料的关联的特性
            if($data['ftgp_id']){
                $addBindFeatureData = array(
                    'bm_id' => $filter['bm_id'],
                    'feature_group_id' => $data['ftgp_id'],
                );
                $basicMaterialFeatureGrpObj->insert($addBindFeatureData);
                $addBindFeatureData = null;
            }

            //保存物料扩展信息
            $updateExtData = array(
                'cost' => $data['cost'] ? $data['cost'] : 0.00,
                'retail_price' => $data['retail_price'] ? $data['retail_price'] : 0.00,
                'weight' => $data['weight'] ? $data['weight'] : 0.00,
                'unit' => $data['unit'],
            );
            $basicMaterialExtObj->update($updateExtData, $filter);
        }else{
            $result = array('msg'=>'基础物料更新失败', 'rsp'=>'fail');
        }

        return $result;
    }
}